<?php

namespace App\Admin\Controllers;

use App\Models\BookModel;
use App\Models\BookShelf;
use Encore\Admin\Controllers\AdminController;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use Illuminate\Support\MessageBag;

class BookShelfController extends AdminController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '书架管理';

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $grid = new Grid(new BookShelf());

        $grid->column('id', __('Id'));
        $grid->column('book_id', '书本')->display(function ($book_id) {
                return BookModel::where('id',$book_id)->value('book_title');
        });
        $grid->column('type', '类型')->using([1=>'企业书籍',2=>'塾生书籍']);
        $grid->column('is_opend','是否公开')->using([ 1=>'全部可见',2=>'会员可见']);

        $grid->column('sort','排序');

        $grid->column('created_at','创建时间');
        $grid->column('updated_at', '更新时间');

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {
        $show = new Show(BookShelf::findOrFail($id));

        $show->field('id', __('Id'));
        $show->book_id('书本')->as(function ($book_id) {
            return BookModel::where('id',$book_id)->value('book_title');
        });
        $show->field('type', '类型')->using([1=>'企业书籍',2=>'塾生书籍']);
        $show->field('is_opend','是否公开')->using([ 1=>'全部可见',2=>'会员可见']);

        $show->field('sort','排序');

        $show->field('created_at','创建时间');
        $show->field('updated_at', '更新时间');

        return $show;
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new BookShelf());

        $form->select('book_id', '书本')->options(function ($book_id){
            return BookModel::/*where('id',$book_id)->*/pluck('book_title','id');
        });
        $form->select('type', '类型')->options([1=>'企业书籍',2=>'塾生书籍']);
        $form->select('is_opend','是否公开')->options([ 1=>'全部可见',2=>'会员可见']);

        $form->text('sort','排序');

        //保存前回调
        $form->saving(function (Form $form) {
            $book_id = $form->book_id;
            $type = $form->type;
            $check_shelf = BookShelf::where('book_id',$book_id)->where('type',$type)->first();
            if(!empty($check_shelf)){
                $error = new MessageBag([
                    'title'   => '无法添加',
                    'message' => '请勿添加重复的书本',
                ]);
                return back()->with(compact('error'));
            }
        });
        return $form;
    }
}
